<%@page import="java.util.Date"%>
<%@page import="weaver.conn.RecordSet" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
         import="com.zlgs.cqyf.vote.ConnectionUtil" %>
<%@ page import="com.alibaba.fastjson.*" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="weaver.hrm.User" %>
<%@page import="java.text.SimpleDateFormat"%>
<%
    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json; charset=utf-8");
    JSONObject retObject = new JSONObject();
    retObject.put("code", 200);
    retObject.put("msg", "操作成功");
    String userId ="";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
         Object requestType = request.getParameter("requestType");
        if(null != requestType && !"".equals(requestType.toString())&&"mobile".equals(requestType.toString())){
  				Object userIdObj = request.getParameter("userId");
  				if(null == userIdObj || "".equals(userIdObj.toString())){
  					throw  new RuntimeException("该用户不存在于OA!");
  				}
  				 userId = userIdObj.toString();
  				 String userSQL = "select top 1 * from HrmResource where   loginid = N'"+userId+"' ORDER BY ID DESC";
  				 RecordSet  userSet= new RecordSet();
  				 userSet.executeSql(userSQL);
  				 if(userSet.next()){
  				 }else{
  					 throw  new RuntimeException("该用户不存在于OA!");
  				 }
  			}else{
            if (!ConnectionUtil.is_local){
                    User user = HrmUserVarify.getUser (request , response) ;
                    if (null == user)  throw new RuntimeException("请重新登录");
                    userId = user.getLoginid();
                }
            }

        // URL 参数
        Integer awardsSubnameId = Integer.parseInt(request.getParameter("awardsSubnameId"));
        Object key = request.getParameter("searchKey");
        JSONArray array = new JSONArray();
        if (awardsSubnameId != null) {
            // 数据库查询
            String sql= "select * from vote_awards_participator  " +
            "where  awards_subname_id ="+awardsSubnameId+
            (key==null||key.equals("")?"":" and (member_names like N'%"+key.toString()+"%' OR nominator_name like N'%"+key.toString()+"%'   )") +
            " order by win_status DESC";

            RecordSet set = new RecordSet();
            set.executeSql(sql);
            while (set.next()) {
                String awardsId  = set.getString("awards_id");
                Integer id  = set.getInt("id");
                sql = "SELECT * FROM vote_awards  where id="+awardsId;
                RecordSet set7 = new RecordSet();
                set7.executeSql(sql);
                boolean active = false;                     // 活动是否正在进行
                String votesSameStr = "1";
                while(set7.next()){
                    String votestr    =  set7.getString("votes");           // 已配置每人票数
                    Long startTime = 0L;
                    votesSameStr = set7.getString("votes_same");
                    String startTimeStr  = set7.getString("start_time");
                    if(null!=startTimeStr && !"".equals(startTimeStr)){
                        try{
                            startTime = sdf.parse(startTimeStr).getTime();
                        }catch(Exception e){}
                    }

                    Long endTime = 0L;
                    String endTimeStr  = set7.getString("end_time");
                    if(null!=endTimeStr && !"".equals(endTimeStr)){
                        try{
                            endTime = sdf.parse(endTimeStr).getTime();
                        }catch(Exception e){}
                    }
                      // 2.1查询本次投票子奖项的状态是否结束
                    sql = "select * from vote_awards_subname where id="+awardsSubnameId;
                    RecordSet set8 = new RecordSet();
                    set8.executeSql(sql);
                    while(set8.next()){
                        if (set8.getInt("status")==1) active = true;
                    }
                    // 2.2 子奖项未结束是，校验活动时间是否结束
                    if (active){
                        active = startTime<endTime;
                    }
                    //活动是否结束
                    if(active){
                    	Long now  =	new Date().getTime();
                    	active = now < endTime;
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("flowerStatus",false);
                // 数据库查询
                RecordSet set9  = new RecordSet();
                sql = "SELECT * from vote_awards_flower where awards_participator_id="+id+" and user_id= N'"+userId+"'";
                set9.executeQuery(sql);
                RecordSet set10  = null;
                String queryCountSql = "";
                while (set9.next()){
                    jsonObject.put("flowerStatus",true);
                    break;
                }
                jsonObject.put("activesql",sql);
                jsonObject.put("active",active);
                String awardsParticipatorId = set.getString("id");
                jsonObject.put("id", awardsParticipatorId);                                      // 参与名单id
                jsonObject.put("memberNames", set.getString("member_names"));                // 被提名名称
                jsonObject.put("nominatorName", set.getString("nominator_name"));             // 被提名名称
                jsonObject.put("nominatorDeptName", set.getString("nominator_dept_name"));    // 被提名部门名称
                jsonObject.put("nominatorPosition", set.getString("nominator_position"));     // 被提名职位
                jsonObject.put("nominatorPhoto", set.getString("nominator_photo"));           // 被提名照片（参与人头像）
                jsonObject.put("nominatorType", set.getString("nominator_type"));                // 被提名类型：1 个人 2 团队
                jsonObject.put("winStatus", set.getString("win_status"));                    // 是否获奖 0 未获奖 1 获奖
                jsonObject.put("flowerNum", set.getString("flower_num"));                        // 送花数量
                jsonObject.put("messageNum", set.getString("message_num"));                      // 留言数量
                jsonObject.put("votesNum", set.getString("votes_num"));                          // 得票数量
                jsonObject.put("applicantDeptName", set.getString("applicant_dept_name"));
                jsonObject.put("nominatorProjectName", set.getString("nominator_project_name"));  //新增字段 项目名称
                jsonObject.put("applicantSecondDeptName", set.getString("applicant_second_dept_name"));  // 申请人二级部门
                jsonObject.put("nominatorSecondDeptName", set.getString("nominator_second_dept_name"));  // 提名人二级部门
                jsonObject.put("voteStatus",true);
                if(active){
                	String countNumStr = "0";
                	try{
	                	set10 = new RecordSet();
	                	queryCountSql= "select count(*)  AS num from vote_awards_ballot where awards_participator_id = N'"+awardsParticipatorId+"' AND user_id = N'"+userId+"'";
	                	set10.executeQuery(queryCountSql);
	                	if(set10.next()){
	                		countNumStr = set10.getString("num");
	                	}
                	}catch(Exception e){}
                	Integer votesame = 1;
                	try{
	                	votesame = Integer.valueOf(votesSameStr);
                	}catch(Exception e){}
                	Integer countNum = 0;
                	try{
                		countNum = Integer.valueOf(countNumStr);
                	}catch(Exception e){}

                	jsonObject.put("voteStatus", countNum>=votesame);

                }
                array.add(jsonObject);
            }
        }
        retObject.put("data", array);
    } catch (Exception e) {
        e.printStackTrace();
        retObject.put("code", -1);
        retObject.put("msg", e.getMessage());
    } finally {
        PrintWriter printWriter = response.getWriter();
        printWriter.append(retObject.toJSONString());
        if (printWriter != null) printWriter.close();
    }
%>
